"use client";
import Search from '@/app/ui/search';
import dayjs from "dayjs";
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger
} from "@/app/ui/components/ui/dropdown-menu";
import { deleteChatFlow, getChatFlowList } from '@/server/flowise/data';
import { ChevronDown, Copy, Delete, Download, Edit, FilePenLine, Info, Plus } from 'lucide-react';
import { Button } from '@/app/ui/components/ui/button';
import { Tabs, TabsList, TabsTrigger } from '@/app/ui/components/ui/tabs';
import { useEffect, useMemo, useState } from 'react';
import clsx from 'clsx';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/app/ui/components/ui/card';
import Link from 'next/link';
import { useToast } from '@/app/ui/components/ui/use-toast';
import { useRouter } from 'next/navigation';
import useDialogStore from '@/lib/store/useDialogStore';
import { Input } from '@/app/ui/components/ui/input';

export default function Chatflows({
    searchParams,
}: {
    searchParams?: {
        query?: string;
        page?: string;
    };
}) {
    const [showType, setShowType] = useState<string>('list');
    const [dataSource, setDataSource] = useState<any[]>([]);
    const { toast } = useToast();
    const { showDialog } = useDialogStore();
    const router = useRouter();

    const query = searchParams?.query || '';

    useEffect(() => {
        loadData();
    }, []);

    const loadData = () => {
        getChatFlowList().then(records => {
            setDataSource(records);
        });
    }

    const items = useMemo(() => {
        return dataSource.filter(i => i.name.includes(query) || i.category.includes(query))
    }, [query, dataSource]);

    // 渲染分类
    const renderCategoryListDom = (categoryList = []) => {
        return <div className='flex gap-3'>
            {
                categoryList.map((i: string, index: number) => {
                    return <span key={i + '_' + index} className='bg-[#00000014] text-sm text-[#616161] px-2 py-1 rounded-2xl'>{i}</span>
                })
            }
        </div>
    }

    // 渲染节点图标
    const renderNodeListDom = (nodeImageList = []) => {
        const length = nodeImageList.length;
        return <div className='flex gap-2 items-center'>
            {
                nodeImageList.slice(0, 5).map((i: string, index: number) => {
                    return <div key={i + '_' + index} className='bg-[#e0e0e075] rounded-full p-1'>
                        <img width={25} height={25} alt="" src={i} />
                    </div>
                })
            }
            {length > 5 ? <div className='text-[#666]'>+ {length - 5} More</div> : null}
        </div>
    }

    const onRename = (item: any) => {
        setTimeout(() => {
            showDialog({
                title: "重命名",
                content: <div className="px-2 py-4">
                    <Input className="text-base w-full" placeholder="请输入名称" />
                </div>,
                onOk: () => {
                    return true;
                }
            });
        }, 0);
    }

    const onAddCategory = (item: any) => {
        setTimeout(() => {
            showDialog({
                title: "设置标签",
                content: <div className="px-2 py-4">
                    <Input className="text-base w-full" placeholder="请输入标签名称" />
                </div>,
                onOk: () => {
                    return true;
                }
            });
        }, 0);
    }

    // 复制
    const onCopy = (item: any) => {

    }

    // 导出
    const onExportFile = (item: any) => {
        const flowData = JSON.parse(item.flowData);
        const json = JSON.stringify(flowData, null, 2);
        const blob = new Blob([json], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${item?.name || '未知'}.json`;
        a.download = `${item?.name || '未知'}.json`;
        a.click();
    }

    // 删除
    const onDeleteItem = (id: string) => {
        setTimeout(() => {
            showDialog({
                title: "提示",
                content: <div className='flex gap-2 items-center'>
                    <Info className='h-5 w-5 text-[orange]' />
                    <div>确认删除吗</div>
                </div>,
                okBtnClassName: 'focus-visible:none bg-red-500 text-blue-50 hover:bg-red-500/90 dark:bg-red-900 dark:text-blue-50 dark:hover:bg-red-900/90',
                onOk: () => {
                    deleteChatFlow(id).then(res => {
                        if (res.affected === 1) {
                            toast({
                                title: (<div className="text-secondary">删除成功!</div> as any),
                                description: dayjs().format('YYYY-MM-DD HH:mm:ss')
                            });
                            loadData();
                        } else {
                            toast({
                                title: (<div className="text-[orange]">删除失败!</div> as any),
                                description: dayjs().format('YYYY-MM-DD HH:mm:ss')
                            });
                        }
                    });
                    return true;
                }
            });
        }, 0);
    }

    // 去编辑
    const onEdit = (id?: string) => {
        router.push(`/flowise/canvas/${id}`);
    }

    return <>
        <div className="w-full">
            <div className='flex items-center justify-between'>
                <h1 className='font-bold'>ChatFlows</h1>
                <div className='flex items-center justify-end gap-2'>
                    <Search placeholder="输入名称或者分类搜索" />
                    <Tabs defaultValue={showType} onValueChange={setShowType}>
                        <TabsList>
                            <TabsTrigger value="list">列表</TabsTrigger>
                            <TabsTrigger value="card">卡片</TabsTrigger>
                        </TabsList>
                    </Tabs>
                    <Link href="/flowise/canvas">
                        <Button>
                            <Plus className="mr-1 h-4 w-4" />新增
                        </Button>
                    </Link>
                </div>
            </div>
            <div className="mt-6 flow-root">
                <div className="overflow-x-auto">
                    <div className="inline-block min-w-full align-middle">
                        <div className="overflow-hidden rounded-md">
                            <div className={clsx(['grid grid-cols-3 gap-3', showType === 'list' && 'hidden'])}>
                                {items?.map((item: any) => (
                                    <Card key={item.id} onClick={() => onEdit(item.id)}>
                                        <CardHeader>
                                            <CardTitle>{item.name}</CardTitle>
                                            <CardDescription>{item.isPublic ? '已发布' : '未发布'}</CardDescription>
                                        </CardHeader>
                                        <CardContent>{renderCategoryListDom(item.categoryList)}</CardContent>
                                        <CardFooter>{renderNodeListDom(item.nodeImageList)}</CardFooter>
                                    </Card>
                                ))}
                            </div>
                            <table className={clsx(["min-w-full rounded-md text-gray-900 table", showType == 'card' && 'hidden'])}>
                                <thead className="rounded-md bg-gray-50 text-left text-sm font-normal">
                                    <tr>
                                        <th scope="col" className="px-4 py-5 font-medium whitespace-nowrap">
                                            名称
                                        </th>
                                        <th scope="col" className="px-3 py-5 font-medium whitespace-nowrap">
                                            分类
                                        </th>
                                        <th scope="col" className="px-3 py-5 font-medium whitespace-nowrap">
                                            节点
                                        </th>
                                        <th scope="col" className="px-3 py-5 font-medium whitespace-nowrap">
                                            更新时间
                                        </th>
                                        <th scope="col" className="px-4 py-5 font-medium whitespace-nowrap">
                                            操作
                                        </th>
                                    </tr>
                                </thead>

                                <tbody className="divide-y divide-gray-200 text-gray-900">
                                    {items.map((item: any) => (
                                        <tr key={item.id} className="group">
                                            <td className="whitespace-nowrap bg-white px-4 py-5 text-sm font-bold">
                                                <div className='cursor-pointer underline text-main' onClick={() => onEdit(item.id)}>{item.name}</div>
                                            </td>
                                            <td className="whitespace-nowrap bg-white px-4 py-5 text-sm">
                                                {renderCategoryListDom(item.categoryList)}
                                            </td>
                                            <td className="whitespace-nowrap bg-white px-4 py-5 text-sm">
                                                {renderNodeListDom(item.nodeImageList)}
                                            </td>
                                            <td className="whitespace-nowrap bg-white px-4 py-5 text-sm">
                                                {dayjs(item.updatedDate).format('YYYY-MM-DD HH:mm')}
                                            </td>
                                            <td className="whitespace-nowrap bg-white px-4 py-5 text-sm">
                                                <DropdownMenu>
                                                    <DropdownMenuTrigger asChild>
                                                        <Button variant="ghost" size="sm" className="rounded-xl cursor-pointer">
                                                            操作<ChevronDown color="#666" className="h-5 w-5 ml-1" />
                                                        </Button>
                                                    </DropdownMenuTrigger>
                                                    <DropdownMenuContent className="w-40">
                                                        <DropdownMenuItem className='cursor-pointer' onClick={() => onRename(item)}>
                                                            <Edit className="mr-2 h-4 w-4 text-gray-400" />
                                                            <span>重命名</span>
                                                        </DropdownMenuItem>
                                                        <DropdownMenuItem className='cursor-pointer' onClick={() => onCopy(item)} disabled>
                                                            <Copy className="mr-2 h-4 w-4 text-gray-400" />
                                                            <span>复制</span>
                                                        </DropdownMenuItem>
                                                        <DropdownMenuItem className='cursor-pointer' onClick={() => onExportFile(item)}>
                                                            <Download className="mr-2 h-4 w-4 text-gray-400" />
                                                            <span>导出</span>
                                                        </DropdownMenuItem>
                                                        <DropdownMenuSeparator />
                                                        <DropdownMenuItem className='cursor-pointer' onClick={() => onAddCategory(item)}>
                                                            <FilePenLine className="mr-2 h-4 w-4 text-gray-400" />
                                                            <span>设置标签</span>
                                                        </DropdownMenuItem>
                                                        <DropdownMenuSeparator />
                                                        <DropdownMenuItem className='cursor-pointer' onClick={() => { onDeleteItem(item.id) }}>
                                                            <Delete className="mr-2 h-4 w-4 text-gray-400" />
                                                            <span>删除</span>
                                                        </DropdownMenuItem>
                                                    </DropdownMenuContent>
                                                </DropdownMenu>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </>;
}
